﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using ActionLogic;
using BehaviorModel;
using BehaviorModel.Block;
using QSDesigner.Windows.Models;

namespace QSDesigner.Windows
{
    /// <summary>
    /// Interaction logic for AvgQueueLengthByChannelsWindow.xaml
    /// </summary>
    public partial class AvgQueueLengthByChannelsWindow : Window, IAvgQueueLengthByChannelsWindow, IUpdatableWindow
    {
        private DesignerCanvas DesignerCanvas { get; set; }
        private List<DesignerItem> ServiceChannels { get; set; }
        private Dictionary<Guid, String> ServiceChannelsNames { get; set; }

        public DispatcherTimer DispatcherTimer { get; set; }

        public AvgQueueLengthByChannelsWindow(DesignerCanvas canvas)
        {
            InitializeComponent();

            DesignerCanvas = canvas;

            UpdateModel();
            
            ServiceChannelsNames = ServiceChannels.ToDictionary(sc => sc.Block.Id, sc => sc.BlockName);

            DispatcherTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(1000) };
            DispatcherTimer.Tick += (s, a) =>
                                         {
                                             Action action = UpdateChart;
                                             Dispatcher.Invoke(action);
                                         };
        }

        public void UpdateChart()
        {
            var stat = StatisticController.GetInstance().Statistic.AvgQueueLengthByChannels;

            var statistic = ServiceChannelsNames.Keys.Select(key => new AvgQlChannelsModel
            {
                BlockName = ServiceChannelsNames[key],
                QueueLength = stat[key],
                UniqueColor = ServiceChannels.Find(sc => sc.Block.Id == key).UniqueColor
            }).ToList();

            ((ColumnSeries)columnChart.Series[0]).ItemsSource = statistic;                  
        }

        public void StartFetchData()
        {
            // Start the timer
            DispatcherTimer.Start();
        }

        public void StopFetchData()
        {
            DispatcherTimer.Stop();
        }

        public void UpdateModel()
        {
            ServiceChannels = DesignerCanvas.Children.OfType<DesignerItem>().ToList().Where(x => x.Block.Type == BlockType.ServiceChannel).ToList();
        }

    }
}
